package com.example.easybuy.controller;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/news")
public class NewsController {
    
    // 模拟数据存储
    private List<News> newsList = new ArrayList<>();
    private long idCounter = 1;
    
    // 创建新闻
    @PostMapping
    public News createNews(@RequestBody News news) {
        news.setId(idCounter++);
        newsList.add(news);
        return news;
    }
    
    // 获取所有新闻
    @GetMapping
    public List<News> getAllNews() {
        return newsList;
    }
    
    // 根据ID获取新闻
    @GetMapping("/{id}")
    public News getNewsById(@PathVariable Long id) {
        return newsList.stream()
                .filter(n -> n.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
    
    // 更新新闻
    @PutMapping("/{id}")
    public News updateNews(@PathVariable Long id, @RequestBody News updatedNews) {
        News news = getNewsById(id);
        if (news != null) {
            news.setTitle(updatedNews.getTitle());
            news.setContent(updatedNews.getContent());
            return news;
        }
        return null;
    }
    
    // 删除新闻
    @DeleteMapping("/{id}")
    public void deleteNews(@PathVariable Long id) {
        newsList.removeIf(n -> n.getId().equals(id));
    }
    
    // 新闻数据类
    static class News {
        private Long id;
        private String title;
        private String content;
        
        // 构造函数
        public News() {}
        
        public News(String title, String content) {
            this.title = title;
            this.content = content;
        }
        
        // Getter和Setter方法
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }
}